package com.bigknow.appstore.web.base.controller;

import com.bigknow.appstore.web.base.controller.entity.TreeNode;
import com.bigknow.appstore.web.base.entity.Permission;
import com.bigknow.appstore.web.base.service.impl.PermissionService;
import com.bigknow.appstore.web.framework.util.AuthenticateUserUtil;
import org.apache.commons.lang3.StringUtils;
import org.mongodb.morphia.Datastore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by 李科风 on 2016-06-03.
 */
@Controller
@RequestMapping(value = "/user-index")
public class UserIndexController {

    @Autowired
    private Datastore ds;

    @Autowired
    private PermissionService service;


    @RequestMapping("/get-menu-tree")
    @ResponseBody
    public List<TreeNode> getMenuTree(String key) {
        List<TreeNode> nodes = new ArrayList<>();
        createTreeNode(nodes);
        if (StringUtils.isEmpty(key)) {
            return nodes;
        } else {
            try {
                key = URLDecoder.decode(key, "utf-8");
            } catch (UnsupportedEncodingException e) {
            }
            nodes = filterByKey(nodes, key);
        }
        return nodes;
    }

    private void createTreeNode(List<TreeNode> nodes) {
        List<Permission> permissions = service.getMenuTreeByUserId(AuthenticateUserUtil.getUserId());
        permissions.stream().filter(permission -> permission.getId().equals("DVCON"))
                .forEach(permission -> createTree(nodes, permission));
    }

    private void createTree(List<TreeNode> nodes, Permission permission) {
        if (permission.getChildren() == null) return;
        permission.getChildren().forEach(perm -> {
            TreeNode td = new TreeNode(perm.getCode(), perm.getParentCode(), perm.getName(),
                    perm.getPageUrl(), perm.getIconCss());
            //TODO://预留接口
            if (perm.getCode().equals("XXXXX")) {
                td.setOpen(true);
            }
            nodes.add(td);
            createTree(nodes, perm);
        });
    }

    static List<TreeNode> filterByKey(List<TreeNode> nodes, String key) {
        List<TreeNode> selectedNodes = nodes.stream().filter(n -> n.getName().toLowerCase().contains(key.toLowerCase())).collect(Collectors.toList());
        List<TreeNode> res = new ArrayList<>();
        while (!selectedNodes.isEmpty()) {
            selectedNodes.forEach(n -> {
                if (!res.contains(n)) {
                    res.add(n);
                    n.setOpen(true);
                }
            });
            selectedNodes = getParentNode(nodes, selectedNodes);
        }
        return res;
    }

    private static List<TreeNode> getParentNode(List<TreeNode> nodes, List<TreeNode> selectedNodes) {
        List<TreeNode> res = new ArrayList<>();
        selectedNodes.forEach(n -> {
            if (!StringUtils.isEmpty(n.getpId())) {
                nodes.forEach(p -> {
                    if (p.getId().equals(n.getpId())) {
                        res.add(p);
                    }
                });
            }
        });
        return res;
    }
}
